import { login } from '@/api/user'
import { setToken, removeToken, getToken } from '@/utils/auth'
import { getInfo } from '@/api/user'
import { constantRoutes } from '@/router/index'
import { resetRouter } from '@/router/index'
const state = {
  token: getToken() || '',
  userinfo: {},
  newroutes: constantRoutes,
  btnlist: []
}
const getters = {}
const mutations = {
  setToken(state, newtoken) {
    state.token = newtoken
    setToken(newtoken)
  },
  removeToken(state) {
    state.token = ''
    state.userinfo = {}
    removeToken()
  },
  userinfo(state, info) {
    state.userinfo = info
  },
  setrouter(state, newroute) {
    state.newroutes = [...constantRoutes, ...newroute]
  },
  setbtnlist(state, btn) {
    state.btnlist = btn
  }
}
function transListToTreeData(list, rootValue) {
  const arr = []
  list.forEach(item => {
    if (item.pid === rootValue) {
      // 找到了匹配的节点
      // 当前节点的id 和 当前节点的子节点的pid是想等的
      const children = transListToTreeData(list, item.id) // 找到的节点的子节点
      if (children.length) item.children = children // 将子节点赋值给当前节点
      arr.push(item)
    }
  })
  return arr
}
function loadview(component) {
  try {
    if (component === 'layout') {
      return require('@/layout/index.vue').default
    } else {
      return require('@/views/' + component + '.vue').default
    }
  } catch (error) {
    return require('@/views/404.vue').default
  }
}
const actions = {
  async getlogin(context, data) {
    const res = await login(data)
    // console.log(res)
    context.commit('setToken', res.token)
  },
  async getInfo(context) {
    const res = await getInfo()
    console.log(res)
    context.commit('userinfo', res.userInfo)
    context.commit('setbtnlist', res.btnList)
    return res.menuList
  },
  logout(context) {
    context.commit('removeToken')
    resetRouter()
  },
  getnewroute(context, payload) {
    const midrouter = payload.map(item => {
      return {
        path: item.path,
        name: item.mark,
        meta: {
          title: item.title,
          icon: item.icon
        },
        hidden: item.is_show !== 1,
        redirect: item.redirect,
        component: loadview(item.component),
        pid: item.pid,
        id: item.id
      }
    })
    return transListToTreeData(midrouter, 0)
  }
}
const modules = {}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
  modules
}
